<!-- src/components/Login.vue -->
<template>
  <div class="login-container">
    <div class="login-box">
      <h2>用户登录</h2>
      <el-form
          :model="loginForm"
          :rules="rules"
          ref="loginForm"
          class="login-form">
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              show-password>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="handleLogin"
              :loading="loading"
              style="width: 100%">
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.doLogin()
        }
      })
    },

    doLogin() {
      this.loading = true

      const loginData = {
        username: this.loginForm.username,
        password: this.loginForm.password
      }

      request.post('/api/login', loginData)
          .then(response => {
            console.log('完整响应数据:', response)
            return response
          })
          .then(response => {
            // 根据后端实际返回的数据结构处理
            if (this.isSuccessResponse(response)) {
              this.handleLoginSuccess(response)
            } else {
              this.handleLoginFailure(response)
            }
          })
          .catch(error => {
            this.handleLoginError(error)
          })
          .finally(() => {
            this.loading = false
          })
    },

    isSuccessResponse(response) {
      // 检查多种可能的成功标识
      return response &&
          (response.success === true ||
              response.code === 200 ||
              (response.success !== undefined && response.success !== false))
    },

    handleLoginSuccess(response) {
      console.log('登录成功，响应数据:', response)

      // 保存用户信息到本地存储
      try {
        const userData = response.user || response.data || response
        if (userData) {
          localStorage.setItem('user', JSON.stringify(userData))
        }

        // 如果有token也保存
        const token = response.token || (response.data && response.data.token)
        if (token) {
          localStorage.setItem('token', token)
        }

        this.$message.success('登录成功')

        // 延迟跳转以确保消息显示
        setTimeout(() => {
          this.$router.push('/users')
        }, 500)
      } catch (e) {
        console.error('保存用户信息失败:', e)
        this.$message.success('登录成功，但保存信息时出现问题')
        this.$router.push('/users')
      }
    },

    handleLoginFailure(response) {
      console.log('登录失败，响应数据:', response)

      // 处理多种可能的错误信息格式
      const errorMsg = response.message ||
          response.msg ||
          response.error ||
          '登录失败'

      this.$message.error(errorMsg)
    },

    handleLoginError(error) {
      console.error('登录请求错误:', error)

      let errorMsg = '登录请求失败'

      if (error.response) {
        // 服务器返回了响应，但状态码不是2xx
        console.log('错误响应:', error.response)
        errorMsg = error.response.data?.message ||
            error.response.data?.msg ||
            error.response.statusText ||
            `登录失败 (${error.response.status})`
      } else if (error.request) {
        // 请求已发出但没有收到响应
        errorMsg = '网络连接失败，请检查网络'
      } else {
        // 其他错误
        errorMsg = error.message || errorMsg
      }

      this.$message.error(errorMsg)
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 400px;
  padding: 40px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.login-form {
  margin-top: 30px;
}

.login-box h2 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

@media (max-width: 480px) {
  .login-box {
    width: 90%;
    margin: 0 5%;
    padding: 30px 20px;
  }
}
</style>
